'use strict'
const child_process = require('child_process')
const SUN = require('../base/sun')
const log4js = require('log4js')
let nodes = SUN.serConfig.nodeConfig
let logger = log4js.getLogger('logger')


class NodeSerHandle {
    constructor() {
        this.children = {}
    }
    start() {
        for (let node of nodes) {
            if (!node.path || (node.path && node.path.length === 0)) {
                continue
            }
            let child = child_process.spawn(process.execPath, [node.path, 'serType=' + node.type, 'name=' + node.name])
            child.node = node
            this.children[node.name] = child
            child.stdout.on('data', function(data) {
                data = data.slice(0, data.length - 1)
                logger.info(this.node.name, data.toString())
            }.bind(child))
            child.stderr.on('data', function(data) {
                console.info(this.node.name + ' stderr:', data.toString())
            }.bind(child))
            child.on('exit', function(code) {
                console.info(this.node.name + ' 节点进程出错:' + code)
            }.bind(child))
        }
    }
}
let nodeSerHandle = new NodeSerHandle()
module.exports = nodeSerHandle
